package com.lanxin.xx.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.lanxin.hr.entity.ZzAccount;
import com.lanxin.hr.service.IZzEmployeeService;
import com.lanxin.xx.entity.XxInformation;
import com.lanxin.xx.mapper.XxInformationMapper;
import com.lanxin.xx.service.IXxInformationService;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.*;
import java.net.URLEncoder;
import java.time.LocalDateTime;
import java.util.List;

/**
 * <p>
 * 服务实现类
 * </p>
 *
 * @author zyq
 * @since 2025-07-26
 */
@Service
public class XxInformationServiceImpl extends ServiceImpl<XxInformationMapper, XxInformation> implements IXxInformationService {

    private static final Logger logger = Logger.getLogger(XxInformationServiceImpl.class);

    /**
     * 上传目录相对路径
     */
    private static final String UPLOAD_RELATIVE_PATH = "/WEB-INF/static/upload/xx/";

    /**
     * 添加公告信息（包含文件上传）
     */
    @Override
    @Transactional(propagation = Propagation.REQUIRED)
    public boolean addInformation(XxInformation information, MultipartFile file, HttpServletRequest request) {
        try {
            // 处理文件上传（与目标代码一致的判断逻辑）
            if (file != null && !file.isEmpty()) {
                String filePath = handleFileUpload(file, request);
                information.setFile(filePath);
                logger.info("文件上传成功，路径：" + filePath);
            }

            HttpSession session = request.getSession();
            ZzAccount account = (ZzAccount) session.getAttribute("account");
            information.setCreator(account.getAid());

            // 设置发布时间
            information.setPublishDate(LocalDateTime.now());

            // 保存信息
            boolean saveResult = save(information);
            if (saveResult) {
                logger.info("信息添加成功，ID：" + information.getOid());
            } else {
                logger.warn("信息添加失败，数据：" + information);
            }
            return saveResult;
        } catch (Exception e) {
            logger.error("添加信息失败", e);
            throw new RuntimeException("添加信息失败：" + e.getMessage());
        }
    }

    /**
     * 更新信息（包含文件上传）
     */
    @Override
    @Transactional(propagation = Propagation.REQUIRED)
    public boolean updateInformation(XxInformation information, MultipartFile file, HttpServletRequest request) {
        try {
            // 校验ID是否存在
            Integer oid = information.getOid();
            if (oid == null) {
                logger.error("更新信息失败：ID不能为空");
                throw new RuntimeException("更新信息失败：ID不能为空");
            }

            // 处理新文件上传（与目标代码一致的判断逻辑）
            if (file != null && !file.isEmpty()) {
                // 删除旧文件（复用目标代码风格的删除方法）
                deleteOldFile(oid, request);
                // 上传新文件
                String filePath = handleFileUpload(file, request);
                information.setFile(filePath);
                logger.info("更新信息时，新文件上传成功，路径：" + filePath);
            }

            // 更新信息（保留原发布时间）
            boolean updateResult = updateById(information);
            if (updateResult) {
                logger.info("信息更新成功，ID：" + oid);
            } else {
                logger.error("信息更新失败，ID：" + oid + "，数据：" + information);
            }
            return updateResult;
        } catch (Exception e) {
            logger.error("更新信息失败", e);
            throw new RuntimeException("更新信息失败：" + e.getMessage());
        }
    }

    /**
     * 获取最新的指定类型信息
     */
    @Override
    public List<XxInformation> getLatestInformation(Integer typeId, int limit) {
        QueryWrapper<XxInformation> query = new QueryWrapper<>();
        query.eq("typeid", typeId)
                .orderByDesc("publishDate")
                .last("limit " + limit);
        List<XxInformation> list = list(query);
        return list;
    }

    /**
     * 处理文件上传
     */
    private String handleFileUpload(MultipartFile file, HttpServletRequest request) throws IOException {
        // 获取上传目录绝对路径（通过request获取真实路径）
        String uploadAbsPath = request.getServletContext().getRealPath(UPLOAD_RELATIVE_PATH);
        // 创建目录（如果不存在）
        File uploadDir = new File(uploadAbsPath);
        if (!uploadDir.exists()) {
            uploadDir.mkdirs();
        }
        // 生成唯一文件名（系统时间戳+原始文件名，与目标代码一致）
        String originalFilename = file.getOriginalFilename();
        String newFileName = System.currentTimeMillis() + "_" + originalFilename;
        // 保存文件
        File destFile = new File(uploadAbsPath + newFileName);
        file.transferTo(destFile);
        // 返回前端访问用的相对路径（与目标代码路径格式一致）
        return "upload/xx/" + newFileName;
    }

    /**
     * 删除旧文件（与目标代码deleteOldFile逻辑完全一致）
     */
    private void deleteOldFile(Integer oid, HttpServletRequest request) {
        // 获取旧信息
        XxInformation oldInfo = getById(oid);
        if (oldInfo == null || StringUtils.isEmpty(oldInfo.getFile())) {
            return;
        }
        // 构建旧文件绝对路径（拼接WEB-INF/static前缀）
        String oldFilePath = request.getServletContext().getRealPath("/WEB-INF/static/" + oldInfo.getFile());
        File oldFile = new File(oldFilePath);
        if (oldFile.exists()) {
            boolean deleted = oldFile.delete();
            if (deleted) {
                logger.info("旧文件删除成功：" + oldInfo.getFile());
            } else {
                logger.warn("旧文件删除失败：" + oldFilePath);
            }
        }
    }
}